package com.wyy.aspect;

import com.wyy.error.BusinessException;
import com.wyy.error.EnumBusinessError;
import com.wyy.util.TokenUtils;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: 吴磊
 * @program: blog
 * @create: 2021-04-19 21:54
 */
@Component
@Aspect
public class LoginAspect {
    @Autowired
    private TokenUtils tokenUtils;

    @Pointcut("execution(* com.wyy.web.*.token*(..))")
    private void login() {
    }

    /**
     * 用来检测请求头中是否存在Token
     *
     * @throws BusinessException
     */
    @Before(value = "com.wyy.aspect.LoginAspect.login()")
    public void getToken() throws BusinessException {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        String token = request.getHeader("Authorization");
        boolean bool = tokenUtils.inspectionToken(token);
        if (!bool) {
            throw new BusinessException(EnumBusinessError.USER_NOT_LOGIN, "请登录后再执行此操作");
        }
    }
}
